package fun.ty13.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import fun.ty13.commom.R;
import fun.ty13.entity.Employee;
import fun.ty13.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 员工控制器
 *
 * @author ShanHai
 * @date 2022/11/25 21:01
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录
     *
     * @param employee 员工
     * @param request  请求
     * @return {@link R}<{@link Employee}>
     */
    @PostMapping ("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request) {
        //1.将页面提交密码进行md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2.根据用户名和密码查询员工
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(wrapper);
        //3.判断员工是否存在
        if (emp == null) {
            return R.error("用户名不存在");
        }
        //4.判断密码是否正确
        if (!emp.getPassword().equals(password)) {
            return R.error("密码错误");
        }
        //5.查看员工是否被禁用
        if (emp.getStatus() == 0) {
            return R.error("该用户已被禁用");
        }
        //6.将员工信息存入session
        request.getSession().setAttribute("employee", emp.getId());
        //7.将对象密码置空
        emp.setPassword(null);
        //8.返回员工信息
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

}
